﻿using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Lucene.Linq.Storage.EntityFramework
{
    /// <summary>
    /// 
    /// </summary>
    public static class DataContextExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataContext"></param>
        /// <param name="id"></param>
        /// <typeparam name="TTable"></typeparam>
        /// <typeparam name="TPrimaryKey"></typeparam>
        /// <returns></returns>
        public static TTable Get<TTable, TPrimaryKey>(this DataContext dataContext, TPrimaryKey id)
            where TTable : class
        {
            Table<TTable> table = dataContext.GetTable<TTable>();
            ParameterExpression e = Expression.Parameter(typeof(TTable), "e");
            MetaType metaType = dataContext.Mapping.GetMetaType(typeof(TTable));
            string identityColumnName = metaType.IdentityMembers[0].Name;

            PropertyInfo propInfo = typeof(TTable).GetProperty(identityColumnName);
            MemberExpression m = Expression.MakeMemberAccess(e, propInfo);
            ConstantExpression c = Expression.Constant(id, typeof(TPrimaryKey));
            BinaryExpression b = Expression.Equal(m, c);
            Expression<Func<TTable, bool>> lambda = Expression.Lambda<Func<TTable, bool>>(b, e);
            return table.SingleOrDefault(lambda);
        }
    }
}